package com.bnu.attachment.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnu.attachment.Entity.Attachment;
import com.bnu.attachment.Entity.Result;
import com.bnu.attachment.Mapper.AttachmentMapper;
import com.bnu.attachment.Service.AttachmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
@Transactional
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements AttachmentService{

	@Resource
    private AttachmentMapper attachmentMapper;

    //此方法用来展示每一条政策对应附件的路径
    //attachment表中的attach字段用来存放附件路径


    @Override
    public Object Show(HttpServletRequest request) {
        //获得相应政策序号
        Integer pid = Integer.valueOf(request.getParameter("a_pid"));//接收到的政策编号变量
        //条件构造器
        QueryWrapper<Attachment> queryWrapper = new QueryWrapper<Attachment>();
        //设置查询条件
        queryWrapper.select("attach").lt("a_pid",pid);
        return attachmentMapper.selectList(queryWrapper);
    }

    @Override
    public Object Upload(HttpServletRequest request) throws ServletException {
        Result<String> result = new Result<>();

        int MAX_SIZE = 102400 * 102400; //定义上载文件的最大字节
        String rootPath; // 创建根路径的保存变量
        DataInputStream in = null; //声明文件读入类
        FileOutputStream fileOut = null;
        String remoteAddr = request.getRemoteAddr(); //取得客户端的网络地址
        String serverName = request.getServerName(); //获得服务器的名字
        String realPath = request.getRealPath("/");//取得互联网程序的绝对地址
        realPath = realPath.substring(0,realPath.lastIndexOf("\\"));
        rootPath = realPath + "\\upload\\"; //创建文件的保存目录
        //out.println("上传文件保存目录为"+rootPath);
        String contentType = request.getContentType(); //取得客户端上传的数据类型
        try{
            if(contentType.contains("multipart/form-data")){
                in = new DataInputStream(request.getInputStream()); //读入上传的数据
                int formDataLength = request.getContentLength();
                if(formDataLength > MAX_SIZE){
                    //out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
                    result.setErrCode(-1);
                    result.setErrMessage("上传的文件字节数过长");
                }

                byte[] dataBytes = new byte[formDataLength]; //保存上传文件的数据
                int byteRead = 0;
                int totalBytesRead = 0;
                while(totalBytesRead < formDataLength){ //上传的数据保存在byte数组
                    byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
                    totalBytesRead += byteRead;
                }
                String file = new String(dataBytes); //根据byte数组创建字符串
                String saveFile = file.substring(file.indexOf("filename=\"") + 10); //取得上传的数据的文件名
                saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1,contentType.length());//取得数据的分隔字符串
                String fileName = rootPath + saveFile;
                int pos;
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n",pos) + 1;
                pos = file.indexOf("\n",pos) + 1;
                pos = file.indexOf("\n",pos) + 1;
                int boundaryLocation = file.indexOf(boundary,pos) - 4;
                int startPos = ((file.substring(0,pos)).getBytes()).length;//取得文件数据的开始的位置
                int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length; //取得文件数据的结束的位置
                File checkFile = new File(fileName); //检查上载文件是否存在
                if(checkFile.exists()){
                    //  out.println("<p>" + saveFile + "文件已经存在.</p>");
                    result.setErrCode(0);
                    result.setErrMessage("文件已存在");
                }

                File fileDir = new File(rootPath);//检查上载文件的目录是否存在
                if(!fileDir.exists()){
                    fileDir.mkdirs();
                }
                fileOut = new FileOutputStream(fileName); //创建文件的写出类
                fileOut.write(dataBytes,startPos,(endPos - startPos)); //保存文件的数据
                fileOut.close();

                //上传成功后，向数据库中插入相应附件记录
                int pid = Integer.parseInt(request.getParameter("a_pid"));
                Attachment attachment = new Attachment();
                attachment.setAttach(fileName);
                attachment.setA_pid(pid);
                attachmentMapper.insert(attachment);

                //out.println("<P><font color=red size=5>" + saveFile + "文件成功上传.</font></p>");
            }//对应 if(contentType.indexOf("multipart/form-data") >= 0)

            else{
                String content = request.getContentType();
                //out.println("<p>上传的数据类型不是是multipart/form-data</p>");
                result.setErrCode(1);
                result.setErrMessage("上传的数据类型不是是multipart/form-data");
            }
        }catch(Exception ex)
        {
            throw new ServletException(ex.getMessage());
        }
        return result;
    }

    //下载附件
    @Override
    public void Download(HttpServletRequest request,HttpServletResponse response) {
        response.reset();

        try {
            //接收前台传来的文件路径
            String attach = request.getParameter("attach");
            attach = new String(attach.getBytes("iso8859-1"), "gb2312");
            String path = request.getRealPath("/");
            path = path.substring(0, path.lastIndexOf("\\"));
            path = path + "\\upload\\";
            File fileLoad = new File(path, attach);//下载文件位置：
            response.reset();
            OutputStream o = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(o);
            byte[] b = new byte[500];  //输出文件用的字节数组,每次发送500个字节到输出流：
            response.setHeader("Content-disposition", "attachment;filename=" + new String(attach.getBytes("gb2312"), "iso8859-1")); //客户使用保存文件的对话框
            response.setContentType("application/x-tar");//通知客户文件的MIME类型：
            long fileLength = fileLoad.length();//通知客户文件的长度：
            String length = String.valueOf(fileLength);
            response.setHeader("Content_Length", length);
            FileInputStream in = new FileInputStream(fileLoad);//读取文件,并发送给客户下载:
            int n = 0;
            while ((n = in.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            bos.close();
        } catch (Exception e) {
            System.out.print(e);
        }
        response.reset();
    }
}